//
//  PageTransition.m
//  Staff
//
//  Created by caiyao on 1/13/15.
//
//

#import "PageTransition.h"

@implementation PageTransition

- (void)excute {
    
    NSString *url = [self.command.functionParamsDic objectForKey:@"url"];
    if (url == nil)
    {
        // params is missing fail to handle
        [self excuteNonHookFoundCallback];
        return;
    }
    
    // it is not common method , it need to define in the ui support webview
    NSString *urlToOpen = [[self.command.functionParamsDic objectForKey:@"url"] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    
    NSString *targetLink = [self handlingOpenURL:urlToOpen];
    
    DebugLog(@"opening URL %@ in new modal view: ",targetLink);
    
    if (targetLink)
    {
        //self.targetURL = urlToOpen;
        [[self hookViewController] pageTransaction:targetLink slide:[self.command.functionParamsDic objectForKey:@"slide"]];
        [[NSNotificationCenter defaultCenter] postNotificationName:COMMAND_EXCUTE_DONE_NOTIFICATION object:self];

    }
    else
    {
        // params is missing fail to handle
        [self excuteNonHookFoundCallback];
        return;
    }
}

- (BOOL) needHandleFilePath:(NSString *)filePath
{
    BOOL flag = YES;
    
//    if ([filePath rangeOfString:homeUUID].location != NSNotFound)
//    {
//        flag = NO;
//    }
//    
    return flag;
}

- (NSString *) handlingOpenURL:(NSString *)openURL
{
    DebugLog(@"handlingOpenURL is %@",openURL);
    
    NSString *targetLink = nil;
    
    if (openURL !=nil)
    {
        if ([openURL hasPrefix:@"file:"])
        {
            if ([self needHandleFilePath:openURL]) {
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectory = [paths objectAtIndex:0];
                NSString *targetRootFolder = [NSString stringWithFormat:@"file://%@",documentsDirectory];
                
                targetRootFolder = [targetRootFolder stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
                
                NSString *localFilePath = [openURL substringFromIndex:6];
                
                targetLink = [NSString stringWithString:[targetRootFolder stringByAppendingPathComponent:localFilePath]];
            } else {
                targetLink = [NSString stringWithString:openURL];
            }
        }
        else if ([openURL hasPrefix:@"http:"])
        {
            targetLink = [NSString stringWithString:openURL];
        }
        else if ([openURL hasPrefix:@"https:"])
        {
            targetLink = [NSString stringWithString:openURL];
        }
        else
        {
            targetLink = [NSString stringWithFormat:@"%@%@",@"https://",openURL];
        }
    }
    
    return targetLink;
}


@end
